package com.doughit.music163.core;

import com.doughit.music163.config.Config;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.doughit.music163.config.Config.DRIVER;

public class SongNumberIncrease implements Increase {
    private static final Logger logger = LoggerFactory.getLogger(TotalNumberIncrease.class);
    //歌曲列表id
    private List<String> songIds = Config.SONG_IDS;
    private Pattern songName = Pattern.compile("class=\"f-thide name fc1 f-fl\" title=\"(.*?)\"");
    private static ChromeOptions chromeOptions = new ChromeOptions();
    private static WebDriver driver = null;

    static {
        System.setProperty("webdriver.chrome.driver", DRIVER);
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("headless");
    }

    @Override
    public void start() {
        try {
            driver = new ChromeDriver(chromeOptions);
            invoke();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            driver.quit();
        }
    }

    /**
     * 初始化cookies
     */
    private static void initCookies() {
//        while (true) {
        try {
            JsonArray ja = (JsonArray) new JsonParser().parse(new FileReader("cookies.txt"));
            driver.manage().deleteAllCookies();
            ja.forEach(jsonElement -> {
                JsonObject jo = (JsonObject) jsonElement;
                Cookie cookie = new Cookie.Builder(jo.get("name").getAsString(), jo.get("value").getAsString()).build();
                driver.manage().addCookie(cookie);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
//        }
    }

    private void invoke() {
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
        String s = null;
        driver.get("http://music.163.com/");
        initCookies();
        ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(0));
        driver.switchTo().defaultContent();
        while (true) {
            try {
                for (String playListId : songIds) {
                    driver.get("https://music.163.com/#/song?id=" + playListId);
                    driver.switchTo().frame("contentFrame");
                    WebElement element = driver.findElement(By.cssSelector("[id=content-operation]>a:first-child"));
                    element.click();
                    driver.switchTo().defaultContent();
                    s = driver.getPageSource();
                    Matcher songNameMatcher = songName.matcher(s);
                    if (songNameMatcher.find()) {
                        String songNameStr = songNameMatcher.group(1);
                        logger.info("当前播放------" + songNameStr);
                    } else {
                        logger.info("解析歌曲播放记录或歌曲名失败");
                    }
                    Thread.sleep(1000L * Config.SONG_INTERVAL);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}
